<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="1000px"
    @close="close"
  >
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="上级部门" prop="pid">
        <el-tree-select
          v-model="form.pid"
          :data="treelist"
          filterable
          :render-after-expand="false"
          style="width: 100%"
          check-strictly
          check-on-click-node
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="菜单">
        <div class="vab-tree-border">
          <el-tree
            ref="treeRef"
            :data="list"
            :default-checked-keys="powerArr"
            :default-expanded-keys="[]"
            show-checkbox
            :check-strictly="false"
            :check-on-click-node="true"
            node-key="id"
          >
            <template #default="{ data }">
              <span>{{ data.meta.title }}</span>
            </template>
          </el-tree>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { doEdit, doAdd, getList } from '@/api/roleManagement'
  import { getTree } from '@/api/menuManagement'
  import { convertedTreeNode } from '@/utils/index'

  export default defineComponent({
    name: 'RoleManagementEdit',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        formRef: null,
        treeRef: null,
        form: {
          pid: [],
          rules: '',
        },
        rules: {
          name: [{ required: true, trigger: 'blur', message: '请输入名称' }],
        },
        title: '',
        dialogFormVisible: false,
        list: [],
        treelist: [],
        powerArr: [],
      })

      const showEdit = async (row) => {
        state.powerArr = []
        await fetchData()
        await fetchTreeData()
        if (!row) {
          state.title = '添加'
        } else {
          nextTick(() => {
            // 渲染父级
            if (row.add) {
              state.title = '添加'
              state.form.pid = row.id
            } else {
              state.title = '编辑'
              state.form.pid = row.pid
              state.form = { ...row }
            }
            state.powerArr = row.rules.split(',')
          })
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          btnRolesCheckedList: [],
        }
        state.dialogFormVisible = false
      }
      const fetchData = async () => {
        const {
          data: { list },
        } = await getTree()
        state.list = convertedTreeNode(list)
      }
      const save = () => {
        console.log()
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await doEdit({
              ...state.form,
              ...{
                rules: JSON.parse(JSON.stringify(state.powerArr.toString())),
              },
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }

      const add = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            const { msg } = await doAdd({
              ...state.form,
              ...{
                rules: JSON.parse(JSON.stringify(state.powerArr.toString())),
              },
            })
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }

      const confirm = async () => {
        if (state.title == '编辑') {
          save()
        } else {
          add()
        }
      }

      const fetchTreeData = async () => {
        state.listLoading = true
        const {
          data: { list, total },
        } = await getList()
        state.treelist = convertedTreeNode(list)
        state.total = total
        state.listLoading = false
      }

      onMounted(() => {})
      return {
        ...toRefs(state),
        showEdit,
        close,
        fetchData,
        fetchTreeData,
        save,
        add,
        confirm,
      }
    },
  })
</script>

<style lang="scss" scoped>
  .vab-tree-border {
    width: 100%;
    height: 350px;
    padding: $base-padding;
    overflow-y: auto;
    border: 1px solid #dcdfe6;
    border-radius: $base-border-radius;
  }
</style>
